import { BaseCommand } from '@amcax/base';
import { useEffect } from 'react';
import useStateRef from 'react-usestateref';
import { StyledToggleToolButton } from '../styled';
import { ToolButton } from '../ToolButton';

interface IProps {
  activatedCmdIndex?: number;
  isActivated?: boolean;
  cmds: BaseCommand[];
  className?: string;
}
export const ToggleToolButton = ({
  activatedCmdIndex = -1,
  isActivated = false,
  cmds,
  className,
}: IProps) => {
  const [, setCurrentCmd, currentCmdRef] = useStateRef<BaseCommand>();

  useEffect(() => {
    if (activatedCmdIndex > -1 && cmds.length > 1) {
      activatedCmdIndex = Math.min(activatedCmdIndex, cmds.length - 1);
      setCurrentCmd(cmds[activatedCmdIndex]);
    }
  }, [activatedCmdIndex]);

  useEffect(() => {
    if (cmds.length == 1) {
      setCurrentCmd(isActivated ? cmds[0] : null);
    }
  }, [isActivated]);

  const handleCmdInvoked = (cmd: BaseCommand) => {
    if (cmds.length == 1) {
      setCurrentCmd((prevCmd) => {
        return prevCmd ? null : cmd;
      });
    } else {
      setCurrentCmd(cmd);
    }
  };

  const handleCmdInvokFinished = () => {
    setCurrentCmd(null);
  };

  const getIsActivated = (cmd: BaseCommand) => {
    return currentCmdRef.current ? currentCmdRef.current.id === cmd.id : false;
  };

  return (
    <StyledToggleToolButton>
      {cmds.map((cmd) => {
        return (
          <ToolButton
            cmd={cmd}
            key={cmd.id}
            className={className}
            onCmdInvoked={handleCmdInvoked}
            onCmdInvokFinished={handleCmdInvokFinished}
            activated={getIsActivated(cmd)}
          />
        );
      })}
    </StyledToggleToolButton>
  );
};
